package com.login.framework.utils;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.login.framework.LoginConstants;

public class LogManager {

	private static final String ATTR_DATETIME = "datetime";

	private static final String ATTR_SUCCESS = "success";

	private static final String ATTR_USERNAME = "username";

	private static final String NODE_USER = "user";

	private static final String LOG_PATH = "log.xml";

	private static final String ROOT_TAG = "login-intents";

	private static LogManager instance;

	private Document log;

	public static LogManager get() {
		if (instance == null) {
			instance = new LogManager();
		}
		return instance;
	}

	private LogManager() {
		DocumentBuilderFactory docFactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder docBuilder;
		try {
			docBuilder = docFactory.newDocumentBuilder();

			try {
				log = docBuilder.parse(new FileInputStream(LOG_PATH));
			} catch (Exception e) {
				log = docBuilder.newDocument();
				log.appendChild(log.createElement(ROOT_TAG));
			}

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

	}

	public void log(String username, boolean failed) {
		try {

			Element root = (Element) log.getElementsByTagName(ROOT_TAG).item(0);

			Element user = log.createElement(NODE_USER);
			user.setAttribute(ATTR_USERNAME, username);
			user.setAttribute(ATTR_SUCCESS, Boolean.toString(failed));
			user.setAttribute(ATTR_DATETIME, new SimpleDateFormat(
					LoginConstants.DATE_TIME_FORMAT).format(new Date()));
			root.appendChild(user);

			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(log);
			StreamResult result = new StreamResult(new File(LOG_PATH));
			transformer.transform(source, result);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
